package com.xiaocz.hblsubstitutedriving.activities.navi;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CrossOverlay;
import com.amap.api.maps.model.LatLng;
import com.amap.api.navi.AMapNaviView;
import com.amap.api.navi.enums.NaviType;
import com.amap.api.navi.model.AMapCalcRouteResult;
import com.amap.api.navi.model.AMapModelCross;
import com.amap.api.navi.model.AMapNaviCameraInfo;
import com.amap.api.navi.model.AMapNaviCross;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.AMapTrafficStatus;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.RouteOverlayOptions;
import com.amap.api.navi.view.RouteOverLay;
import com.gyf.barlibrary.ImmersionBar;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.activities.activity.SearchDestinationActivity;
import com.xiaocz.hblsubstitutedriving.utils.NaviUtil;
import com.xiaocz.hblsubstitutedriving.widget.navi.AMapCameraOverlay;
import com.xiaocz.hblsubstitutedriving.widget.navi.CarOverlay;
import com.xiaocz.hblsubstitutedriving.widget.navi.NextTurnTipView;
import com.xiaocz.hblsubstitutedriving.widget.navi.TrafficProgressBar;
import com.xiaocz.hblsubstitutedriving.widget.navi.ZoomInIntersectionView;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 自定义导航
 */
public class NavigationCustomActivity extends BaseNavigationActivity {

    @BindView(R.id.myTrafficBar)
    TrafficProgressBar mTrafficBarView;
    @BindView(R.id.myZoomInIntersectionView)
    ZoomInIntersectionView mZoomInIntersectionView;
    @BindView(R.id.text_next_road_distance)
    TextView textNextRoadDistance;
    @BindView(R.id.text_next_road_name)
    TextView textNextRoadName;
    @BindView(R.id.icon_next_turn_tip)
    NextTurnTipView nextTurnTipView;
    @BindView(R.id.navi_view)
    AMapNaviView mAMapNaviView;

    private AMapCameraOverlay cameraOverlay;
    private CrossOverlay crossOverlay;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_all_custom_navi_view;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mAMapNaviView.onCreate(savedInstanceState);
        initTTS();
        super.init(savedInstanceState);
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColor(R.color.navigation_back).init();
    }

    @Override
    protected void initData() {
        mAMapNaviView.setNaviMode(AMapNaviView.CAR_UP_MODE);//车头模式
        super.initData();
    }

    /**
     * 重新算路
     */
    private void naviRecount() {
        // 初始化成功
        int strategy = 0;
        try {
            //再次强调，最后一个参数为true时代表多路径，否则代表单路径
            strategy = mAMapNavi.strategyConvert(true, false, false, false, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("---------strategy2:" + strategy);
        boolean isSuccess = mAMapNavi.calculateDriveRoute(eList, mWayPointList, strategy);
    }

    @BindView(R.id.btn_ql)
    TextView btnQL;
    private boolean isQL;

    @OnClick({R.id.tv_change, R.id.btn_ql})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_change://更改目的地
                Intent intent = new Intent(mContext, SearchDestinationActivity.class);
                startActivityForResult(intent, 200);
                break;
            case R.id.btn_ql:
                isQL = !isQL;
                if (isQL) {
                    mAMapNaviView.displayOverview();
                    btnQL.setText(getResources().getString(R.string.text_jx));
                } else {
                    mAMapNaviView.recoverLockMode();
                    btnQL.setText(getResources().getString(R.string.text_ql));
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 2) {
            double lat = data.getDoubleExtra("LAT", 0);
            double lng = data.getDoubleExtra("LNG", 0);
            data.getStringExtra("CITY");
            data.getStringExtra("ADDRESS");
            data.getStringExtra("NAME");
            if (lat != 0 && lng != 0) {
                endAddress.setLatitude(lat);
                endAddress.setLongitude(lng);
                eList.clear();
                eList.add(endAddress);
                naviRecount();
            }
        }
    }

    @Override
    protected void initWidgets() {
        super.initWidgets();
        cameraOverlay = new AMapCameraOverlay(this);
        mAMapNaviView.getMap().getUiSettings().setZoomControlsEnabled(false);
        mAMapNaviView.getMap().setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                mAMapNaviView.getMap().setPointToCenter(mAMapNaviView.getWidth() / 2, mAMapNaviView.getHeight() / 2);
                mAMapNaviView.getMap().moveCamera(CameraUpdateFactory.zoomTo(16f));
                carOverlay = new CarOverlay(NavigationCustomActivity.this, null);
            }
        });
    }

    /**
     * ------- 导航基本信息的回调 -----
     */
    @Override
    public void onNaviInfoUpdate(NaviInfo naviInfo) {
        super.onNaviInfoUpdate(naviInfo);
        int allLength = mAMapNavi.getNaviPath().getAllLength();
        //导航路况条 更新
        List<AMapTrafficStatus> trafficStatuses = mAMapNavi.getTrafficStatuses(0, 0);
        mTrafficBarView.update(allLength, naviInfo.getPathRetainDistance(), trafficStatuses);

        //更新路口转向图标
        nextTurnTipView.setIconType(naviInfo.getIconType());

        //更新下一路口 路名及 距离
        textNextRoadName.setText(naviInfo.getNextRoadName());
        textNextRoadDistance.setText(NaviUtil.formatKM(naviInfo.getCurStepRetainDistance()));
        //绘制转弯的箭头
        drawArrow(naviInfo);

    }


    /**
     * GPS 定位信息的回调函数
     *
     * @param location 当前定位的GPS信息
     */
    @Override
    public void onLocationChange(AMapNaviLocation location) {
        if (carOverlay != null && location != null) {
            carOverlay.draw(mAMapNaviView.getMap(), new LatLng(location.getCoord().getLatitude(), location.getCoord().getLongitude()), location.getBearing());
        }
    }


    /**
     * ----- start 路口放大图 start -------
     */
    @Override
    public void showCross(AMapNaviCross aMapNaviCross) {
        mZoomInIntersectionView.setIntersectionBitMap(aMapNaviCross);
        mZoomInIntersectionView.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideCross() {
        mZoomInIntersectionView.setVisibility(View.GONE);
    }

    @Override
    public void showModeCross(AMapModelCross aMapModelCross) {
    }

    @Override
    public void hideModeCross() {
        if (crossOverlay != null) {
            crossOverlay.setVisible(false);
        }
    }

    @Override
    public void updateCameraInfo(AMapNaviCameraInfo[] aMapCameraInfos) {
        if (cameraOverlay != null) {
            cameraOverlay.draw(mAMapNaviView.getMap(), aMapCameraInfos);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        mAMapNaviView.getMap().setOnMapTouchListener(new AMap.OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent motionEvent) {
                handler.sendEmptyMessage(MESSAGE_CAR_UNLOCK);
                handler.removeMessages(MESSAGE_CAR_LOCK);
                handler.sendEmptyMessageDelayed(MESSAGE_CAR_LOCK, 3000);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAMapNaviView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAMapNaviView.onPause();
//        仅仅是停止你当前在说的这句话，一会到新的路口还是会再说的
        mTtsManager.stopSpeaking();
//        停止导航之后，会触及底层stop，然后就不会再有回调了，但是讯飞当前还是没有说完的半句话还是会说完
//        mAMapNavi.stopNavi();
    }

    @Override
    public void onCalculateRouteSuccess(AMapCalcRouteResult aMapCalcRouteResult) {
        AMapNaviPath naviPath = mAMapNavi.getNaviPath();
        if (naviPath != null) {
            if (routeOverLay == null) {
                //初始化路线参数
                routeOverLay = new RouteOverLay(mAMapNaviView.getMap(), naviPath, this);
                BitmapDescriptor smoothTraffic = BitmapDescriptorFactory.fromResource(R.drawable.custtexture_green);
                BitmapDescriptor unknownTraffic = BitmapDescriptorFactory.fromResource(R.drawable.custtexture_no);
                BitmapDescriptor slowTraffic = BitmapDescriptorFactory.fromResource(R.drawable.custtexture_slow);
                BitmapDescriptor jamTraffic = BitmapDescriptorFactory.fromResource(R.drawable.custtexture_bad);
                BitmapDescriptor veryJamTraffic = BitmapDescriptorFactory.fromResource(R.drawable.custtexture_grayred);

                RouteOverlayOptions routeOverlayOptions = new RouteOverlayOptions();
                routeOverlayOptions.setSmoothTraffic(smoothTraffic.getBitmap());
                routeOverlayOptions.setUnknownTraffic(unknownTraffic.getBitmap());
                routeOverlayOptions.setSlowTraffic(slowTraffic.getBitmap());
                routeOverlayOptions.setJamTraffic(jamTraffic.getBitmap());
                routeOverlayOptions.setVeryJamTraffic(veryJamTraffic.getBitmap());
                routeOverLay.setRouteOverlayOptions(routeOverlayOptions);
            }
            if (routeOverLay != null) {
                routeOverLay.setAMapNaviPath(naviPath);
                routeOverLay.addToMap();
            }
//            float bearing = NaviUtil.getRotate(mStartLatlng, naviPath.getCoordList().get(1));
//            if (mStartLatlng != null) {
//                carOverlay.reset();
//                //绘制自车位置
//                carOverlay.draw(mAMapNaviView.getMap(), new LatLng(mStartLatlng.getLatitude(), mStartLatlng.getLongitude()), bearing);
//                if (naviPath.getEndPoint() != null) {
//                    LatLng latlng = new LatLng(naviPath.getEndPoint().getLatitude(), naviPath.getEndPoint().getLongitude());
//                    carOverlay.setEndPoi(latlng);
//                }
//            }
        }
        mAMapNavi.startNavi(NaviType.GPS);//开启模拟导航-EMULATOR
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mAMapNaviView != null) {
            mAMapNaviView.onDestroy();
        }
        mAMapNaviView = null;
        if (mAMapNavi != null) {
            mAMapNavi.stopNavi(); //since 1.6.0 不再在naviview destroy的时候自动执行AMapNavi.stopNavi();请自行执行
            mAMapNavi.destroy();
        }
        mAMapNavi = null;
        if (mTtsManager != null) {
            mTtsManager.destroy();
        }
        mTtsManager = null;
        if (mZoomInIntersectionView != null) {
            mZoomInIntersectionView.recycleResource();
        }
        if (crossOverlay != null) {
            crossOverlay.remove();
        }
        if (cameraOverlay != null) {
            cameraOverlay.destroy();
        }
        if (carOverlay != null) {
            carOverlay.destroy();
        }
        if (routeOverLay != null) {
            routeOverLay.removeFromMap();
            routeOverLay.destroy();
        }
        if (mAMapNaviView != null) {
            mAMapNaviView.onDestroy();
        }
    }
}
